package cn.gov.cbrc.core.db;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import cn.gov.cbrc.core.excp.BaseException;

/**
 * 项目名称：DATA2DW<br>
 * *********************************<br>
 * <P>类名称：DBUtil</P>
 * *********************************<br>
 * <P>类描述：数据链接操作类</P>
 * 创建人：王川<br>
 * 创建时间：Jun 9, 2014 5:12:33 PM<br>
 * 修改人：王川<br>
 * 修改时间：Jun 9, 2014 5:12:33 PM<br>
 * 修改备注：<br>
 * @version 1.0<br>    
 */
public class DBUtil {
	
	private static final Logger logger = LogManager.getLogger(DBUtil.class);
	/**
	 * <p>方法描述:根据jndi获取连接 </p>
	 * <p>方法备注: </p>
	 * @param jndiName
	 * @return
	 * @throws Exception
	 * <p>创建人：王川</p>
	 * <p>创建时间：Jun 9, 2014 5:29:29 PM</p>
	 *
	 */
	public static Connection getConnection(String jndiName) throws SQLException,BaseException{
		Connection conn = ConnectionUtil.getConnection(jndiName);
		if(conn == null)
			throw new BaseException("can't get connection from Datasource-->"+jndiName);
		return conn;
	}
	
	/**
	 * <p>方法描述:事务开始</p>
	 * <p>方法备注: </p>
	 * <p>创建人：王川</p>
	 * <p>创建时间：Jun 9, 2014 5:33:02 PM</p>
	 *
	 */
	public static void beginTransation(String jndiName) throws SQLException,BaseException{
		Connection conn = getConnection(jndiName);
		conn.setAutoCommit(false);
	}
	
	/**
	 * <p>方法描述:事务提交 </p>
	 * <p>方法备注: </p>
	 * <p>创建人：王川</p>
	 * <p>创建时间：Jun 9, 2014 5:33:16 PM</p>
	 * @throws SQLException 
	 *
	 */
	public static void commitTransation(String jndiName) throws SQLException,BaseException{
		Connection conn = getConnection(jndiName);
		if(!conn.getAutoCommit())
			conn.commit();
	}
	
	/**
	 * <p>方法描述:事务回滚 </p>
	 * <p>方法备注: </p>
	 * @throws SQLException
	 * <p>创建人：王川</p>
	 * <p>创建时间：Jun 10, 2014 8:59:39 AM</p>
	 *
	 */
	public static void rollbackTransation(String jndiName) throws SQLException,BaseException{
		Connection conn = getConnection(jndiName);
		if(!conn.getAutoCommit())
			conn.rollback();
	}
	
	/**
	 * <p>方法描述: 根据jndi关闭连接</p>
	 * <p>方法备注: </p>
	 * <p>创建人：王川</p>
	 * <p>创建时间：Jun 9, 2014 5:33:40 PM</p>
	 *
	 */
	public static void closeConnection(String jndiName) {
		Connection conn = ConnectionUtil.getConnectionQuiet(jndiName);
		if(conn==null)
			return;
		else
			try {
				conn.close();
			} catch (SQLException e) {
				logger.info(e);
			}
			finally{
				ConnectionUtil.removeConnection(jndiName);
			}
	}
	
	/**
	 * <p>方法描述:关闭所有连接,在service中最后必须要执行此方法，可看例子 </p>
	 * <p>方法备注: </p>
	 * @throws SQLException
	 * <p>创建人：王川</p>
	 * <p>创建时间：Jun 10, 2014 10:13:17 AM</p>
	 *
	 */
	public static void closeAllConnection() {
		List<Connection> conns = ConnectionUtil.getAllConnection();;
		try {
			for(Connection conn: conns)
				conn.close();
		} catch (SQLException e) {
			logger.info(e);
		}
		finally{
			ConnectionUtil.removeAllConnection();
		}
	}
}
